package com.zjc.tcploadbalance;

import org.springframework.cloud.commons.util.SpringFactoryImportSelector;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.type.AnnotationMetadata;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.function.Predicate;

public class EnableTcpLoadBalanceImportSelector extends SpringFactoryImportSelector<EnableTcpLoadBalance> {


    public String[] selectImports(AnnotationMetadata metadata) {
        String[] imports = super.selectImports(metadata);
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(this.getAnnotationClass().getName(), true));
        boolean autoRegister = attributes.getBoolean("autoRegister");

        List<String> importsList = new ArrayList(Arrays.asList(imports));
        importsList.add("com.zjc.tcploadbalance.config.InstanceConfig");
        importsList.add("com.zjc.tcploadbalance.config.ZookeeperConfig");
        importsList.add("com.zjc.tcploadbalance.controller.LoadBalanceController");
        imports = importsList.toArray(new String[0]);
        Environment env = this.getEnvironment();
        if (ConfigurableEnvironment.class.isInstance(env)) {
            ConfigurableEnvironment configEnv = (ConfigurableEnvironment) env;
            LinkedHashMap<String, Object> map = new LinkedHashMap();
            map.put("tcploadbalance.auto-registration.enabled", autoRegister);
            MapPropertySource propertySource = new MapPropertySource("tcploadbalance", map);
            configEnv.getPropertySources().addLast(propertySource);
        }
        return imports;
    }

    @Override
    protected boolean isEnabled() {
        return false;
    }

    @Override
    public Class<? extends Group> getImportGroup() {
        return null;
    }

    @Override
    public Predicate<String> getExclusionFilter() {
        return null;
    }
}
